package 链表;

public class k个一组反转链表 {
    public class ListNode {
        int val;
        ListNode next;
         ListNode() {}
         ListNode(int val) { this.val = val; }
         ListNode(int val, ListNode next) {
             this.val = val; this.next = next; }
  }
        public ListNode reverseKGroup(ListNode head, int k) {
             ListNode tail=head;
             //将tail移到下一个k结点处
             for (int i=0;i<k;i++){
                 if (tail==null){
                     return head;
                 }
                 tail=tail.next;
             }
             //反转k个一组链表
             ListNode newhead=reverse(head,tail);
             //反转后的head指向下一次反转的头节点
             head.next=reverseKGroup(tail,k);
             return newhead;
        }
       private ListNode reverse(ListNode head, ListNode tail) {
        ListNode newhead=null;
        ListNode next=null;
        while (head!=tail){
            next=head.next;
            head.next=newhead;
            newhead=head;
            head=next;
        }
        return newhead;
    }
}
